#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "queue.h"
#include "mongoose.h"
#include "object.h"

/* query all object instances
 * support GET only  
 * the filter could be:
 * name=xxx and/or id=xxx
 */
int query_object(struct mg_connection *conn,
		const struct mg_request_info *ri,
		const char *uri,
		int mobile,
		struct object_list_t *list,
		process_obj_t proc)
{
	char name[MAX_OBJECT_NAME_SIZE] = {0};
	char sid[8] = {0};
	unsigned int id = -1U;
	int len, r = 0;
	struct object_t *obj = NULL;
	struct object_t *tmp = NULL;
	char *req = ri->query_string;

	printf("%s\n", __func__);
	printf("method: %s\n", ri->request_method);
	printf("request: %s\n", req);

	if (req != NULL) {
		len = strlen(req);
		mg_get_var(req, len, "name", name, 16);
		if (mg_get_var(req, len, "id", sid, 8) != -1) {
			id = atoi(sid);
		}
	}

	LIST_FOREACH_SAFE(obj, list, entries, tmp) {
		if (name[0]) {
			if (strcasecmp(name, obj->name))
				continue;
		}
		if (id != -1U) {
			if (obj->id != id)
				continue;
		}
		proc(conn, obj);
		r++;
	}

	return r;
}
